package com.zhss.dfs.server;

import com.zhss.dfs.server.model.INode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 负责管理内存中的文件目录树的核心组件
 * @author zhonghuashishan
 *
 */
public class FSDirectory {
	
	/**
	 * 内存中的文件目录树
	 */
	private INode dirTree;
	
	public FSDirectory() {
		this.dirTree = new INode("/", 0);
	}

	public INode getDirTree() {
		return dirTree;
	}

	public void setDirTree(INode dirTree) {
		this.dirTree = dirTree;
	}

	/**
	 * 创建目录
	 * @param path 目录路径
	 */
	public void mkdir(String path) {
		// path = /usr/warehouse/hive
		// 你应该先判断一下，“/”根目录下有没有一个“usr”目录的存在
		// 如果说有的话，那么再判断一下，“/usr”目录下，有没有一个“/warehouse”目录的存在
		// 如果说没有，那么就得先创建一个“/warehosue”对应的目录，挂在“/usr”目录下
		// 接着再对“/hive”这个目录创建一个节点挂载上去
	
		synchronized(dirTree) {
			String[] pathes = path.split("/");
			INode parent = dirTree;
			
			for(String splitedPath : pathes) {
				if(splitedPath.trim().equals("")) {
					continue;
				}
				INode dir = findDirectory(parent, splitedPath);
				if(dir != null) {
					parent = dir;
					continue;
				}
				INode child = new INode(splitedPath,0);
				parent.addChild(child);
				parent = child;
			}
		}
		// printDirTree();
	}


	private void getChild(String dirPath, List<INode> children, List<String> dirList) {
		if (children.isEmpty()) {
			dirList.add(dirPath);
			return;
		}
		for (INode child : children) {
			INode childDir = (INode) child;
			dirPath = dirPath + "/" +  childDir.getPath();
			getChild(dirPath, childDir.getChildren(), dirList);
		}

	}

	/**
	 * 对文件目录树递归查找目录
	 * @param dir
	 * @param path
	 * @return
	 */
	private INode findDirectory(INode dir, String path) {
		if(dir.getChildren().size() == 0) {
			return null;
		}
		for(INode child : dir.getChildren()) {
			if(child instanceof INode) {
				INode childDir = (INode) child;
				if((childDir.getPath().equals(path))) {
					return childDir;
				}
			}
		}
		return null;
	}

	public INode findParent(String path) {
		String[] split = path.split("/");
		INode parent = dirTree;
		for (String s : split) {
			if("".equals(s.trim())) {
				continue;
			}
			INode dir = findDirectory(parent, s);
			if (dir != null) {
				parent = dir;
				continue;
			}
			INode child = new INode(s,0);
			parent.addChild(child);
			parent = child;
		}
		return parent;
	}

	public Integer createFile(String path){
		String parentPath = path.substring(0, path.lastIndexOf("/"));
		String fileName = path.substring(path.lastIndexOf("/") + 1);
		INode parent = this.findParent(parentPath);
		List<INode> children = parent.getChildren();
		boolean anyMatch = children.stream().anyMatch(iNode -> iNode.getPath().equals(fileName) && iNode.getType().equals(1));
		if (anyMatch) {
			System.out.println("文件名重复了");
			return 1;
		}
		INode child = new INode(fileName,1);
		parent.addChild(child);
		return 0;
	}

}
